<template>
  <div class="shelf-footer" v-show="isEditMode">
    <div
      class="shelf-footer-tab-wrapper"
      v-for="item in tabs"
      :key="item.index"
      @click="onTabClick(item)"
    >
      <div class="shelf-footer-tab" :class="{ 'is-selected': isSelected }">
        <div
          class="icon-private tab-icon"
          v-if="item.index === 1 && !isPrivate"
        ></div>
        <div
          class="icon-private-see tab-icon"
          v-if="item.index === 1 && isPrivate"
        ></div>
        <div
          class="icon-download tab-icon"
          v-if="item.index === 2 && !isDownload"
        ></div>
        <div
          class="icon-download-remove tab-icon"
          v-if="item.index === 2 && isDownload"
        ></div>
        <div class="icon-move tab-icon" v-if="item.index === 3"></div>
        <div class="icon-shelf tab-icon" v-if="item.index === 4"></div>
        <div class="tab-text" :class="{ 'remove-text': item.index === 4 }">
          {{ label(item) }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { storeShelfMixin } from '../../utils/mixin'
import { saveBookShelf, removeLocalStorage } from '../../utils/localStorage'
import { download } from '../../api/store'
import { removeLocalForage } from '../../utils/localForage'

export default {
  mixins: [storeShelfMixin],
  data() {
    return {
      popupMenu: null
    }
  },
  computed: {
    isSelected() {
      // 选中数组存在并且有选中书籍的时候 不透明
      return this.shelfSelected && this.shelfSelected.length
    },
    // 设置底部4个对象
    tabs() {
      return [
        {
          label: this.$t('shelf.private'),
          label2: this.$t('shelf.noPrivate'),
          index: 1
        },
        {
          label: this.$t('shelf.download'),
          label2: this.$t('shelf.delete'),
          index: 2
        },
        {
          label: this.$t('shelf.move'),
          index: 3
        },
        {
          label: this.$t('shelf.remove'),
          index: 4
        }
      ]
    },
    // 选中的图书是否私密阅读
    isPrivate() {
      if (!this.isSelected) {
        return false
      } else {
        // 只有每一本选中的图书是私密阅读，才会在底部显示私密阅读
        return this.shelfSelected.every(item => item.private)
      }
    },
    // 选中图书是否已下载
    isDownload() {
      if (!this.isSelected) {
        return false
      } else {
        return this.shelfSelected.every(item => item.cache)
      }
    }
  },
  methods: {
    onTabClick(item) {
      if (!this.isSelected) {
        return
      }
      switch (item.index) {
        case 1:
          this.showPrivate()
          break
        case 2:
          this.showDownload()
          break
        case 3:
          this.dialog().show()
          break
        case 4:
          this.showRemove()
          break
        default:
          break
      }
    },
    label(item) {
      switch (item.index) {
        case 1:
          return this.isPrivate ? item.label2 : item.label
        case 2:
          return this.isDownload ? item.label2 : item.label
        default:
          return item.label
      }
    },
    // 私密阅读弹窗
    showPrivate() {
      this.popupMenu = this.popup({
        title: this.isPrivate ? this.$t('shelf.closePrivateTitle') : this.$t('shelf.setPrivateTitle'),
        btn: [
          {
            text: this.isPrivate ? this.$t('shelf.close') : this.$t('shelf.open'),
            click: () => {
              this.setPrivate()
            }
          },
          {
            text: this.$t('shelf.cancel'),
            click: () => {
              this.hidePopup()
            }
          }
        ]
      }).show()
    },
    // 设置私密阅读
    setPrivate() {
      let isPrivate
      // 下面的this.isprivate是计算属性
      // 用来判断所有选中书籍是否都是私密阅读，都是才是私密阅读
      // 有不是的就不是私密阅读，就需要将所有书籍都设置为私密阅读
      if (this.isPrivate) {
        isPrivate = false
      } else {
        isPrivate = true
      }
      this.shelfSelected.forEach(book => {
        book.private = isPrivate
      })
      // console.log(this.shelfSelected)
      this.onComplete()
      if (isPrivate) {
        this.simpleToast(this.$t('shelf.setPrivateSuccess'))
      } else {
        this.simpleToast(this.$t('shelf.closePrivateSuccess'))
      }
    },
    // 离线下载弹窗
    showDownload() {
      this.popupMenu = this.popup({
        title: this.isDownload ? this.$t('shelf.removeDownloadTitle') : this.$t('shelf.setDownloadTitle'),
        btn: [
          {
            text: this.isDownload ? this.$t('shelf.delete') : this.$t('shelf.open'),
            type: this.isDownload ? 'danger' : '',
            click: () => {
              this.setDownload()
            }
          },
          {
            text: this.$t('shelf.cancel'),
            click: () => {
              this.hidePopup()
            }
          }
        ]
      }).show()
    },
    // 设置离线下载
    async setDownload() {
      // let isDownload
      // if (this.isDownload) {
      //   isDownload = false
      // } else {
      //   isDownload = true
      // }
      // this.shelfSelected.forEach(book => {
      //   book.cache = isDownload
      // })
      this.onComplete()
      if (this.isDownload) {
        this.removeSelectedBook()
        this.simpleToast(this.$t('shelf.removeDownloadSuccess'))
      } else {
        // 异步下载所选图书
        await this.downloadSelectedBook()
        saveBookShelf(this.shelfList)
        this.simpleToast(this.$t('shelf.setDownloadSuccess'))
      }
    },
    //下载选中图书
    async downloadSelectedBook() {
      for (let i = 0; i < this.shelfSelected.length; i++) {
        await this.downloadBook(this.shelfSelected[i])
          .then(book => { book.cache = true })
      }
    },
    downloadBook(book) {
      // console.log(book)
      let text = ''
      const toast = this.toast({
        text
      })
      toast.continueShow()
      return new Promise((resolve, reject) => {
        // 调用下载书籍函数 在api中
        download(book, book => {
          // console.log('下载完毕')
          // createAPI的方法
          toast.remove()
          resolve(book)
        }, reject, progressEvent => {
          // console.log(progressEvent)
          // 下载进度计算
          const progress = Math.floor(progressEvent.loaded / progressEvent.total * 100) + '%'
          text = this.$t('shelf.progressDownload').replace('$1', `${book.fileName}.epub(${progress})`)
          // console.log(text)
          // 就会不断改变弹窗进度的显示
          toast.updateText(text)
        })
      })
    },
    // 删除选中的离线书籍
    removeSelectedBook() {
      // console.log('aaa')
      Promise.all(this.shelfSelected.map(book => this.removeBook(book)))
        .then(books => {
          books.map(book => {
            book.cache = false
          })
          saveBookShelf(this.shelfList)
          this.simpleToast(this.$t('shelf.removeDownloadSuccess'))
        })
    },
    removeBook(book) {
      return new Promise((resolve, reject) => {
        // 之前在阅读器中存储了书籍的字体字号等等。。
        removeLocalStorage(`${book.categoryText}/${book.fileName}-info`)
        removeLocalForage(`${book.fileName}`)
        resolve(book)
      })
    },
    // 移除书架弹窗
    showRemove() {
      let title
      if (this.shelfSelected.length) {
        // console.log('aaa')
        //   title = this.$t('shelf.removeBookTitle').replace('$1', `<<${this.shelfSelected[0].title}>>`)
        // } else {
        title = this.$t('shelf.removeBookTitle').replace('$1', this.$t('shelf.selectedBooks'))
      }
      this.popupMenu = this.popup({
        title: title,
        btn: [
          {
            text: this.$t('shelf.removeBook'),
            type: 'danger',
            click: () => {
              this.removeSelected()
            }
          },
          {
            text: this.$t('shelf.cancel'),
            click: () => {
              this.hidePopup()
            }
          }
        ]
      }).show()
    },
    // 将所选书籍移出书架
    removeSelected() {
      // console.log('aaa')
      // shelfList是书架的首页列表，
      // shelfList.itemList是书架列表里面的分类
      this.shelfSelected.forEach(selected => {
        this.setShelfList(this.shelfList.filter(book => {
          if (book.itemList) {
            // 进入到分类中判断
            book.itemList = book.itemList.filter(subBook => {
              return subBook !== selected
            })
          }
          return book !== selected
        }))
      })
      // 也可以这么写
      // this.setShelfList(this.shelfList.filter(book => {
      //   if (book.itemList) {
      //     console.log('aaa')
      //     book.itemList = book.itemList.filter(subBook => this.shelfSelected.indexOf(subBook) < 0)
      //   }
      //   return this.shelfSelected.indexOf(book) < 0
      // }))
      this.setShelfSelected([])
      this.onComplete()
    },
    // 隐藏弹窗
    hidePopup() {
      this.popupMenu.hide()
    },
    // 完成操作
    onComplete() {
      this.hidePopup()
      this.setIsEditMode(false)
      // shelfSelected是shelfList的引用 所以前者变化 后者会跟着变
      // 因为选中的书籍对象都是从书架shelfList中push到选中shelfSelected数组中的。
      saveBookShelf(this.shelfList)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../../assets/styles/global";

.shelf-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 120;
  display: flex;
  width: 100%;
  height: px2rem(48);
  background: white;
  box-shadow: 0 px2rem(-2) px2rem(4) 0 rgba(0, 0, 0, 0.1);
  .shelf-footer-tab-wrapper {
    flex: 1;
    width: 25%;
    height: 100%;
    .shelf-footer-tab {
      height: 100%;
      width: 100%;
      opacity: 0.5;
      @include columnCenter;
      &.is-selected {
        opacity: 1;
      }
      .tab-icon {
        font-size: px2rem(20);
        color: #666;
      }
      .tab-text {
        margin-top: px2rem(5);
        font-size: px2rem(12);
        color: #666;
        &.remove-text {
          color: $color-pink;
        }
      }
      .icon-shelf {
        color: $color-pink;
      }
    }
  }
}
</style>
